using AutoMapper;
using ConsoleApi.Models;
using MESBaseis.Domain.XZY;
using MESData.ErrorCode;
using MESData.Infrastucture.Interface;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;

namespace ConsoleApi.Services.Console
{
    /// <summary>
    /// 控制台服务实现
    /// </summary>
    public class ConsoleService : IConsoleService
    {
        private readonly IBaseRepository<AnnouncementModel> _announcementRepository;
        private readonly IBaseRepository<PurchaseOrderModel> _purchaseOrderRepository;
        private readonly IBaseRepository<ProductionOrderModel> _productionOrderRepository;
        private readonly IBaseRepository<ProductionSalesOrderModel> _productionSalesOrderRepository;
        private readonly IBaseRepository<ApprovalDocumentModel> _approvalDocumentRepository;
        private readonly IBaseRepository<CoreMetricsModel> _coreMetricsRepository;
        private readonly IBaseRepository<StatisticsModel> _statisticsRepository;
        private readonly IBaseRepository<WarehouseModel> _warehouseRepository;
        private readonly IBaseRepository<ProductionItemModel> _productionItemRepository;
        private readonly IBaseRepository<ProcessModel> _processRepository;
        private readonly IMapper _mapper;
        private readonly QueryOptimizationService _queryOptimizationService;
        private readonly IMemoryCache _cache;

        public ConsoleService(
            IBaseRepository<AnnouncementModel> announcementRepository,
            IBaseRepository<PurchaseOrderModel> purchaseOrderRepository,
            IBaseRepository<ProductionOrderModel> productionOrderRepository,
            IBaseRepository<ProductionSalesOrderModel> productionSalesOrderRepository,
            IBaseRepository<ApprovalDocumentModel> approvalDocumentRepository,
            IBaseRepository<CoreMetricsModel> coreMetricsRepository,
            IBaseRepository<StatisticsModel> statisticsRepository,
            IBaseRepository<WarehouseModel> warehouseRepository,
            IBaseRepository<ProductionItemModel> productionItemRepository,
            IBaseRepository<ProcessModel> processRepository,
            IMapper mapper,
            QueryOptimizationService queryOptimizationService,
            IMemoryCache cache)
        {
            _announcementRepository = announcementRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
            _productionOrderRepository = productionOrderRepository;
            _productionSalesOrderRepository = productionSalesOrderRepository;
            _approvalDocumentRepository = approvalDocumentRepository;
            _coreMetricsRepository = coreMetricsRepository;
            _statisticsRepository = statisticsRepository;
            _warehouseRepository = warehouseRepository;
            _productionItemRepository = productionItemRepository;
            _processRepository = processRepository;
            _mapper = mapper;
            _queryOptimizationService = queryOptimizationService;
            _cache = cache;
        }

        #region 通知公告

        public async Task<ApiResult<PagedResultDto<AnnouncementDto>>> GetAnnouncementsAsync(AnnouncementQueryDto query)
        {
            try
            {
                // 优化：使用缓存键避免重复查询
                var cacheKey = $"announcements_{query.Type}_{query.IsActive}_{query.Keyword}_{query.PageIndex}_{query.PageSize}";
                
                if (_cache.TryGetValue(cacheKey, out PagedResultDto<AnnouncementDto> cachedResult))
                {
                    return new ApiResult<PagedResultDto<AnnouncementDto>> { Code = ApiEnum.Success, Msg = "获取成功(缓存)", Data = cachedResult };
                }

                // 优化：构建查询时使用AsNoTracking提高性能
                var queryable = _announcementRepository.GetAll()
                    .AsNoTracking()
                    .Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.Type))
                {
                    queryable = queryable.Where(x => x.Type.Contains(query.Type));
                }

                if (query.IsActive.HasValue)
                {
                    queryable = queryable.Where(x => x.IsActive == query.IsActive.Value);
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.Content.Contains(query.Keyword) || x.Publisher.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);

                // 优化：使用查询优化服务进行分页查询
                var (items, totalCount) = await _queryOptimizationService.GetPagedEntitiesAsync(
                    queryable, query.PageIndex, query.PageSize);

                var result = new PagedResultDto<AnnouncementDto>
                {
                    Items = _mapper.Map<List<AnnouncementDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                // 缓存结果2分钟
                _cache.Set(cacheKey, result, TimeSpan.FromMinutes(2));

                return new ApiResult<PagedResultDto<AnnouncementDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<AnnouncementDto>> { Code = ApiEnum.Error, Msg = $"获取通知公告列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<AnnouncementDto>> GetAnnouncementAsync(int id)
        {
            try
            {
                // 优化：使用编译查询和缓存
                var entity = await _queryOptimizationService.GetAnnouncementByIdAsync(id);
                if (entity == null)
                {
                    return new ApiResult<AnnouncementDto> { Code = ApiEnum.Error, Msg = "通知公告不存在" };
                }

                var result = _mapper.Map<AnnouncementDto>(entity);
                return new ApiResult<AnnouncementDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<AnnouncementDto> { Code = ApiEnum.Error, Msg = $"获取通知公告详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<AnnouncementDto>> CreateAnnouncementAsync(AnnouncementDto dto)
        {
            try
            {
                var entity = _mapper.Map<AnnouncementModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _announcementRepository.CreateAsync(entity);
                var result = _mapper.Map<AnnouncementDto>(entity);
                return new ApiResult<AnnouncementDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<AnnouncementDto> { Code = ApiEnum.Error, Msg = $"创建通知公告失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<AnnouncementDto>> UpdateAnnouncementAsync(AnnouncementDto dto)
        {
            try
            {
                var entity = await _announcementRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<AnnouncementDto> { Code = ApiEnum.Error, Msg = "通知公告不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _announcementRepository.UpdateAsync(entity);
                var result = _mapper.Map<AnnouncementDto>(entity);
                return new ApiResult<AnnouncementDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<AnnouncementDto> { Code = ApiEnum.Error, Msg = $"更新通知公告失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeleteAnnouncementAsync(int id)
        {
            try
            {
                var entity = await _announcementRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "通知公告不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _announcementRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除通知公告失败: {ex.Message}" };
            }
        }

        #endregion

        #region 采购订单

        public async Task<ApiResult<PagedResultDto<PurchaseOrderDto>>> GetPurchaseOrdersAsync(PurchaseOrderQueryDto query)
        {
            try
            {
                // 优化：使用缓存键避免重复查询
                var cacheKey = $"purchaseorders_{query.Status}_{query.OrderType}_{query.Keyword}_{query.PageIndex}_{query.PageSize}";
                
                if (_cache.TryGetValue(cacheKey, out PagedResultDto<PurchaseOrderDto> cachedResult))
                {
                    return new ApiResult<PagedResultDto<PurchaseOrderDto>> { Code = ApiEnum.Success, Msg = "获取成功(缓存)", Data = cachedResult };
                }

                // 优化：构建查询时使用AsNoTracking提高性能
                var queryable = _purchaseOrderRepository.GetAll()
                    .AsNoTracking()
                    .Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.Status))
                {
                    queryable = queryable.Where(x => x.Status.Contains(query.Status));
                }

                if (!string.IsNullOrEmpty(query.OrderType))
                {
                    queryable = queryable.Where(x => x.OrderType.Contains(query.OrderType));
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.OrderNumber.Contains(query.Keyword) || 
                                                    x.Subject.Contains(query.Keyword) || 
                                                    x.SupplierName.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);

                // 优化：使用查询优化服务进行分页查询
                var (items, totalCount) = await _queryOptimizationService.GetPagedEntitiesAsync(
                    queryable, query.PageIndex, query.PageSize);

                var result = new PagedResultDto<PurchaseOrderDto>
                {
                    Items = _mapper.Map<List<PurchaseOrderDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                // 缓存结果2分钟
                _cache.Set(cacheKey, result, TimeSpan.FromMinutes(2));

                return new ApiResult<PagedResultDto<PurchaseOrderDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<PurchaseOrderDto>> { Code = ApiEnum.Error, Msg = $"获取采购订单列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<PurchaseOrderDto>> GetPurchaseOrderAsync(int id)
        {
            try
            {
                // 优化：使用编译查询和缓存
                var entity = await _queryOptimizationService.GetPurchaseOrderByIdAsync(id);
                if (entity == null)
                {
                    return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Error, Msg = "采购订单不存在" };
                }

                var result = _mapper.Map<PurchaseOrderDto>(entity);
                return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Error, Msg = $"获取采购订单详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<PurchaseOrderDto>> CreatePurchaseOrderAsync(PurchaseOrderDto dto)
        {
            try
            {
                var entity = _mapper.Map<PurchaseOrderModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _purchaseOrderRepository.CreateAsync(entity);
                var result = _mapper.Map<PurchaseOrderDto>(entity);
                return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Error, Msg = $"创建采购订单失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<PurchaseOrderDto>> UpdatePurchaseOrderAsync(PurchaseOrderDto dto)
        {
            try
            {
                var entity = await _purchaseOrderRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Error, Msg = "采购订单不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _purchaseOrderRepository.UpdateAsync(entity);
                var result = _mapper.Map<PurchaseOrderDto>(entity);
                return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PurchaseOrderDto> { Code = ApiEnum.Error, Msg = $"更新采购订单失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeletePurchaseOrderAsync(int id)
        {
            try
            {
                var entity = await _purchaseOrderRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "采购订单不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _purchaseOrderRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除采购订单失败: {ex.Message}" };
            }
        }

        #endregion

        #region 生产工单

        public async Task<ApiResult<PagedResultDto<ProductionOrderDto>>> GetProductionOrdersAsync(ProductionOrderQueryDto query)
        {
            try
            {
                var queryable = _productionOrderRepository.GetAll().Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.Status))
                {
                    queryable = queryable.Where(x => x.Status.Contains(query.Status));
                }

                if (!string.IsNullOrEmpty(query.ResponsiblePerson))
                {
                    queryable = queryable.Where(x => x.ResponsiblePerson.Contains(query.ResponsiblePerson));
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.OrderNumber.Contains(query.Keyword) || 
                                                    x.ProductionItem.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);

                var totalCount = await queryable.CountAsync();

                var items = await queryable
                    .Skip((query.PageIndex - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToListAsync();

                var result = new PagedResultDto<ProductionOrderDto>
                {
                    Items = _mapper.Map<List<ProductionOrderDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                return new ApiResult<PagedResultDto<ProductionOrderDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<ProductionOrderDto>> { Code = ApiEnum.Error, Msg = $"获取生产工单列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionOrderDto>> GetProductionOrderAsync(int id)
        {
            try
            {
                var entity = await _productionOrderRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Error, Msg = "生产工单不存在" };
                }

                var result = _mapper.Map<ProductionOrderDto>(entity);
                return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Error, Msg = $"获取生产工单详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionOrderDto>> CreateProductionOrderAsync(ProductionOrderDto dto)
        {
            try
            {
                var entity = _mapper.Map<ProductionOrderModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _productionOrderRepository.CreateAsync(entity);
                var result = _mapper.Map<ProductionOrderDto>(entity);
                return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Error, Msg = $"创建生产工单失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionOrderDto>> UpdateProductionOrderAsync(ProductionOrderDto dto)
        {
            try
            {
                var entity = await _productionOrderRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Error, Msg = "生产工单不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _productionOrderRepository.UpdateAsync(entity);
                var result = _mapper.Map<ProductionOrderDto>(entity);
                return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionOrderDto> { Code = ApiEnum.Error, Msg = $"更新生产工单失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeleteProductionOrderAsync(int id)
        {
            try
            {
                var entity = await _productionOrderRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "生产工单不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _productionOrderRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除生产工单失败: {ex.Message}" };
            }
        }

        #endregion

        #region 销售订单

        public async Task<ApiResult<PagedResultDto<ProductionSalesOrderDto>>> GetProductionSalesOrdersAsync(ProductionSalesOrderQueryDto query)
        {
            try
            {
                var queryable = _productionSalesOrderRepository.GetAll().Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.Status))
                {
                    queryable = queryable.Where(x => x.Status.Contains(query.Status));
                }

                if (!string.IsNullOrEmpty(query.CustomerName))
                {
                    queryable = queryable.Where(x => x.CustomerName.Contains(query.CustomerName));
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.OrderNumber.Contains(query.Keyword) || 
                                                    x.Subject.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);
                var totalCount = await queryable.CountAsync();
                var items = await queryable
                    .Skip((query.PageIndex - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToListAsync();

                var result = new PagedResultDto<ProductionSalesOrderDto>
                {
                    Items = _mapper.Map<List<ProductionSalesOrderDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                return new ApiResult<PagedResultDto<ProductionSalesOrderDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<ProductionSalesOrderDto>> { Code = ApiEnum.Error, Msg = $"获取销售订单列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionSalesOrderDto>> GetProductionSalesOrderAsync(int id)
        {
            try
            {
                var entity = await _productionSalesOrderRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Error, Msg = "销售订单不存在" };
                }

                var result = _mapper.Map<ProductionSalesOrderDto>(entity);
                return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Error, Msg = $"获取销售订单详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionSalesOrderDto>> CreateProductionSalesOrderAsync(ProductionSalesOrderDto dto)
        {
            try
            {
                var entity = _mapper.Map<ProductionSalesOrderModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _productionSalesOrderRepository.CreateAsync(entity);
                var result = _mapper.Map<ProductionSalesOrderDto>(entity);
                return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Error, Msg = $"创建销售订单失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionSalesOrderDto>> UpdateProductionSalesOrderAsync(ProductionSalesOrderDto dto)
        {
            try
            {
                var entity = await _productionSalesOrderRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Error, Msg = "销售订单不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _productionSalesOrderRepository.UpdateAsync(entity);
                var result = _mapper.Map<ProductionSalesOrderDto>(entity);
                return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionSalesOrderDto> { Code = ApiEnum.Error, Msg = $"更新销售订单失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeleteProductionSalesOrderAsync(int id)
        {
            try
            {
                var entity = await _productionSalesOrderRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "销售订单不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _productionSalesOrderRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除销售订单失败: {ex.Message}" };
            }
        }

        #endregion

        #region 审批单据

        public async Task<ApiResult<PagedResultDto<ApprovalDocumentDto>>> GetApprovalDocumentsAsync(ApprovalDocumentQueryDto query)
        {
            try
            {
                var queryable = _approvalDocumentRepository.GetAll().Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.DocumentType))
                {
                    queryable = queryable.Where(x => x.DocumentType.Contains(query.DocumentType));
                }

                if (!string.IsNullOrEmpty(query.Status))
                {
                    queryable = queryable.Where(x => x.Status.Contains(query.Status));
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.DocumentNumber.Contains(query.Keyword) || 
                                                    x.Applicant.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);
                var totalCount = await queryable.CountAsync();
                var items = await queryable
                    .Skip((query.PageIndex - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToListAsync();

                var result = new PagedResultDto<ApprovalDocumentDto>
                {
                    Items = _mapper.Map<List<ApprovalDocumentDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                return new ApiResult<PagedResultDto<ApprovalDocumentDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<ApprovalDocumentDto>> { Code = ApiEnum.Error, Msg = $"获取审批单据列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ApprovalDocumentDto>> GetApprovalDocumentAsync(int id)
        {
            try
            {
                var entity = await _approvalDocumentRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Error, Msg = "审批单据不存在" };
                }

                var result = _mapper.Map<ApprovalDocumentDto>(entity);
                return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Error, Msg = $"获取审批单据详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ApprovalDocumentDto>> CreateApprovalDocumentAsync(ApprovalDocumentDto dto)
        {
            try
            {
                var entity = _mapper.Map<ApprovalDocumentModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _approvalDocumentRepository.CreateAsync(entity);
                var result = _mapper.Map<ApprovalDocumentDto>(entity);
                return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Error, Msg = $"创建审批单据失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ApprovalDocumentDto>> UpdateApprovalDocumentAsync(ApprovalDocumentDto dto)
        {
            try
            {
                var entity = await _approvalDocumentRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Error, Msg = "审批单据不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _approvalDocumentRepository.UpdateAsync(entity);
                var result = _mapper.Map<ApprovalDocumentDto>(entity);
                return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ApprovalDocumentDto> { Code = ApiEnum.Error, Msg = $"更新审批单据失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeleteApprovalDocumentAsync(int id)
        {
            try
            {
                var entity = await _approvalDocumentRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "审批单据不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _approvalDocumentRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除审批单据失败: {ex.Message}" };
            }
        }

        #endregion

        #region 核心指标和统计

        public async Task<ApiResult<List<CoreMetricsDto>>> GetCoreMetricsAsync(DateTime? startDate = null, DateTime? endDate = null)
        {
            try
            {
                var queryable = _coreMetricsRepository.GetAll().Where(x => !x.IsDeleted);

                if (startDate.HasValue)
                {
                    queryable = queryable.Where(x => x.Date >= startDate.Value);
                }

                if (endDate.HasValue)
                {
                    queryable = queryable.Where(x => x.Date <= endDate.Value);
                }

                var items = await queryable.OrderByDescending(x => x.Date).ToListAsync();
                var result = _mapper.Map<List<CoreMetricsDto>>(items);
                return new ApiResult<List<CoreMetricsDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<CoreMetricsDto>> { Code = ApiEnum.Error, Msg = $"获取核心指标失败: {ex.Message}" };
            }
        }

        /// <summary>
        /// 获取今日核心指标 - 重新设计，确保数据真实一致
        /// </summary>
        public async Task<ApiResult<CoreMetricsDto>> GetTodayCoreMetricsAsync()
        {
            try
            {
                var today = DateTime.Today;
                var tomorrow = today.AddDays(1);



                // 1. 查询今日销售订单数据 - 根据CreateTime精确查询
                var todaySalesOrders = await _productionSalesOrderRepository.GetAll()
                    .Where(x => !x.IsDeleted && 
                               x.CreateTime >= today && 
                               x.CreateTime < tomorrow)
                    .ToListAsync();

                // 2. 查询今日采购订单数据 - 根据CreateTime精确查询
                var todayPurchaseOrders = await _purchaseOrderRepository.GetAll()
                    .Where(x => !x.IsDeleted && 
                               x.CreateTime >= today && 
                               x.CreateTime < tomorrow)
                    .ToListAsync();



                // 4. 计算核心指标 - 确保与图表数据完全一致
                var salesRevenue = todaySalesOrders.Sum(x => x.TotalAmount);
                var salesOrderCount = todaySalesOrders.Count;
                var purchaseExpense = todayPurchaseOrders.Sum(x => x.TotalAmount);
                var purchaseOrderCount = todayPurchaseOrders.Count;

                // 5. 计算回款和付款（简化处理，实际应该查询相关表）
                var collection = salesRevenue * 0.85m; // 假设85%回款率
                var paidAmount = purchaseExpense; // 假设采购订单就是已付款

                var todayMetrics = new CoreMetricsDto
                {
                    Date = today,
                    SalesRevenue = salesRevenue,
                    SalesOrderCount = salesOrderCount,
                    PurchaseExpense = purchaseExpense,
                    PurchaseOrderCount = purchaseOrderCount,
                    Collection = collection,
                    PaidAmount = paidAmount,
                    Remarks = $"实时计算 - 销售订单: {salesOrderCount}笔(¥{salesRevenue:N2}), 采购订单: {purchaseOrderCount}笔(¥{purchaseExpense:N2})"
                };



                return new ApiResult<CoreMetricsDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = todayMetrics };
            }
            catch (Exception ex)
            {
                return new ApiResult<CoreMetricsDto> { Code = ApiEnum.Error, Msg = $"获取今日核心指标失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<List<StatisticsDto>>> GetStatisticsAsync(StatisticsQueryDto query)
        {
            try
            {
                var queryable = _statisticsRepository.GetAll().Where(x => !x.IsDeleted);

                if (query.StartDate.HasValue)
                {
                    queryable = queryable.Where(x => x.Date >= query.StartDate.Value);
                }

                if (query.EndDate.HasValue)
                {
                    queryable = queryable.Where(x => x.Date <= query.EndDate.Value);
                }

                if (!string.IsNullOrEmpty(query.Type))
                {
                    queryable = queryable.Where(x => x.Type == query.Type);
                }

                if (!string.IsNullOrEmpty(query.TimeRange))
                {
                    queryable = queryable.Where(x => x.TimeRange == query.TimeRange);
                }

                var items = await queryable.OrderByDescending(x => x.Date).ToListAsync();
                var result = _mapper.Map<List<StatisticsDto>>(items);
                return new ApiResult<List<StatisticsDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<StatisticsDto>> { Code = ApiEnum.Error, Msg = $"获取统计数据失败: {ex.Message}" };
            }
        }

        #endregion

        #region 仓库

        public async Task<ApiResult<PagedResultDto<WarehouseDto>>> GetWarehousesAsync(WarehouseQueryDto query)
        {
            try
            {
                var queryable = _warehouseRepository.GetAll().Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.WarehouseType))
                {
                    queryable = queryable.Where(x => x.WarehouseType.Contains(query.WarehouseType));
                }

                if (!string.IsNullOrEmpty(query.Status))
                {
                    queryable = queryable.Where(x => x.Status.Contains(query.Status));
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.WarehouseName.Contains(query.Keyword) || 
                                                    x.Manager.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);
                var totalCount = await queryable.CountAsync();
                var items = await queryable
                    .Skip((query.PageIndex - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToListAsync();

                var result = new PagedResultDto<WarehouseDto>
                {
                    Items = _mapper.Map<List<WarehouseDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                return new ApiResult<PagedResultDto<WarehouseDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<WarehouseDto>> { Code = ApiEnum.Error, Msg = $"获取仓库列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<WarehouseDto>> GetWarehouseAsync(int id)
        {
            try
            {
                var entity = await _warehouseRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<WarehouseDto> { Code = ApiEnum.Error, Msg = "仓库不存在" };
                }

                var result = _mapper.Map<WarehouseDto>(entity);
                return new ApiResult<WarehouseDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<WarehouseDto> { Code = ApiEnum.Error, Msg = $"获取仓库详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<WarehouseDto>> CreateWarehouseAsync(WarehouseDto dto)
        {
            try
            {
                var entity = _mapper.Map<WarehouseModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _warehouseRepository.CreateAsync(entity);
                var result = _mapper.Map<WarehouseDto>(entity);
                return new ApiResult<WarehouseDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<WarehouseDto> { Code = ApiEnum.Error, Msg = $"创建仓库失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<WarehouseDto>> UpdateWarehouseAsync(WarehouseDto dto)
        {
            try
            {
                var entity = await _warehouseRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<WarehouseDto> { Code = ApiEnum.Error, Msg = "仓库不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _warehouseRepository.UpdateAsync(entity);
                var result = _mapper.Map<WarehouseDto>(entity);
                return new ApiResult<WarehouseDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<WarehouseDto> { Code = ApiEnum.Error, Msg = $"更新仓库失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeleteWarehouseAsync(int id)
        {
            try
            {
                var entity = await _warehouseRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "仓库不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _warehouseRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除仓库失败: {ex.Message}" };
            }
        }

        #endregion

        #region 生产物品

        public async Task<ApiResult<PagedResultDto<ProductionItemDto>>> GetProductionItemsAsync(ProductionItemQueryDto query)
        {
            try
            {
                var queryable = _productionItemRepository.GetAll().Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.ItemType))
                {
                    queryable = queryable.Where(x => x.ItemType.Contains(query.ItemType));
                }

                if (query.WarehouseId.HasValue)
                {
                    queryable = queryable.Where(x => x.WarehouseId == query.WarehouseId.Value);
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.ItemNumber.Contains(query.Keyword) || 
                                                    x.ItemName.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);
                var totalCount = await queryable.CountAsync();
                var items = await queryable
                    .Skip((query.PageIndex - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToListAsync();

                var result = new PagedResultDto<ProductionItemDto>
                {
                    Items = _mapper.Map<List<ProductionItemDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                return new ApiResult<PagedResultDto<ProductionItemDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<ProductionItemDto>> { Code = ApiEnum.Error, Msg = $"获取生产物品列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionItemDto>> GetProductionItemAsync(int id)
        {
            try
            {
                var entity = await _productionItemRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProductionItemDto> { Code = ApiEnum.Error, Msg = "生产物品不存在" };
                }

                var result = _mapper.Map<ProductionItemDto>(entity);
                return new ApiResult<ProductionItemDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionItemDto> { Code = ApiEnum.Error, Msg = $"获取生产物品详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionItemDto>> CreateProductionItemAsync(ProductionItemDto dto)
        {
            try
            {
                var entity = _mapper.Map<ProductionItemModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _productionItemRepository.CreateAsync(entity);
                var result = _mapper.Map<ProductionItemDto>(entity);
                return new ApiResult<ProductionItemDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionItemDto> { Code = ApiEnum.Error, Msg = $"创建生产物品失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProductionItemDto>> UpdateProductionItemAsync(ProductionItemDto dto)
        {
            try
            {
                var entity = await _productionItemRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProductionItemDto> { Code = ApiEnum.Error, Msg = "生产物品不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _productionItemRepository.UpdateAsync(entity);
                var result = _mapper.Map<ProductionItemDto>(entity);
                return new ApiResult<ProductionItemDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionItemDto> { Code = ApiEnum.Error, Msg = $"更新生产物品失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeleteProductionItemAsync(int id)
        {
            try
            {
                var entity = await _productionItemRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "生产物品不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _productionItemRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除生产物品失败: {ex.Message}" };
            }
        }

        #endregion

        #region 工序

        public async Task<ApiResult<PagedResultDto<ProcessDto>>> GetProcessesAsync(ProcessQueryDto query)
        {
            try
            {
                var queryable = _processRepository.GetAll().Where(x => !x.IsDeleted);

                if (!string.IsNullOrEmpty(query.Status))
                {
                    queryable = queryable.Where(x => x.Status.Contains(query.Status));
                }

                if (!string.IsNullOrEmpty(query.ProcessType))
                {
                    queryable = queryable.Where(x => x.ProcessType.Contains(query.ProcessType));
                }

                if (!string.IsNullOrEmpty(query.Keyword))
                {
                    queryable = queryable.Where(x => x.DocumentNumber.Contains(query.Keyword) || 
                                                    x.ProcessName.Contains(query.Keyword));
                }

                queryable = queryable.OrderByDescending(x => x.CreateTime);
                var totalCount = await queryable.CountAsync();
                var items = await queryable
                    .Skip((query.PageIndex - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToListAsync();

                var result = new PagedResultDto<ProcessDto>
                {
                    Items = _mapper.Map<List<ProcessDto>>(items),
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize
                };

                return new ApiResult<PagedResultDto<ProcessDto>> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<PagedResultDto<ProcessDto>> { Code = ApiEnum.Error, Msg = $"获取工序列表失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProcessDto>> GetProcessAsync(int id)
        {
            try
            {
                var entity = await _processRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProcessDto> { Code = ApiEnum.Error, Msg = "工序不存在" };
                }

                var result = _mapper.Map<ProcessDto>(entity);
                return new ApiResult<ProcessDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProcessDto> { Code = ApiEnum.Error, Msg = $"获取工序详情失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProcessDto>> CreateProcessAsync(ProcessDto dto)
        {
            try
            {
                var entity = _mapper.Map<ProcessModel>(dto);
                entity.CreateTime = DateTime.Now;
                entity.IsDeleted = false;

                await _processRepository.CreateAsync(entity);
                var result = _mapper.Map<ProcessDto>(entity);
                return new ApiResult<ProcessDto> { Code = ApiEnum.Success, Msg = "创建成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProcessDto> { Code = ApiEnum.Error, Msg = $"创建工序失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<ProcessDto>> UpdateProcessAsync(ProcessDto dto)
        {
            try
            {
                var entity = await _processRepository.GetValue(dto.Id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<ProcessDto> { Code = ApiEnum.Error, Msg = "工序不存在" };
                }

                _mapper.Map(dto, entity);
                entity.UpdateTime = DateTime.Now;

                await _processRepository.UpdateAsync(entity);
                var result = _mapper.Map<ProcessDto>(entity);
                return new ApiResult<ProcessDto> { Code = ApiEnum.Success, Msg = "更新成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProcessDto> { Code = ApiEnum.Error, Msg = $"更新工序失败: {ex.Message}" };
            }
        }

        public async Task<ApiResult<bool>> DeleteProcessAsync(int id)
        {
            try
            {
                var entity = await _processRepository.GetValue(id);
                if (entity == null || entity.IsDeleted)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "工序不存在" };
                }

                entity.IsDeleted = true;
                entity.UpdateTime = DateTime.Now;

                await _processRepository.UpdateAsync(entity);
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = $"删除工序失败: {ex.Message}" };
            }
        }

        #endregion

        #region 图表数据

        /// <summary>
        /// 获取销售统计图表数据 - 重新设计，确保数据真实一致
        /// </summary>
        public async Task<ApiResult<ChartDataDto>> GetSalesChartDataAsync(string timeRange)
        {
            try
            {

                
                var chartData = new ChartDataDto
                {
                    TimeRange = timeRange,
                    Type = "sales"
                };

                // 1. 根据时间范围计算开始和结束日期
                var (startDate, endDate) = GetDateRange(timeRange);
                var timeLabels = GetTimeLabels(timeRange);

                // 2. 查询图表数据
                var chartDataPoints = await _queryOptimizationService.GetChartDataOptimizedAsync<ProductionSalesOrderModel>(
                    startDate, endDate, timeRange);

                // 3. 设置时间标签
                chartData.TimeLabels = timeLabels;
                
                // 4. 确保数据点数量与时间标签数量匹配
                var orderAmounts = new List<decimal>();
                var orderCounts = new List<int>();
                
                // 5. 根据时间范围选择不同的数据映射策略
                if (timeRange == "year")
                {
                    // 年度视图：按月映射数据
                    var startDateForGrouping = startDate.Date;
                    for (int i = 0; i < timeLabels.Count; i++)
                    {
                        var currentMonth = startDateForGrouping.AddMonths(i);
                        var dataPoint = chartDataPoints.FirstOrDefault(x => 
                            x.Date.HasValue && 
                            x.Date.Value.Year == currentMonth.Year && 
                            x.Date.Value.Month == currentMonth.Month);
                        
                        if (dataPoint != null)
                        {
                            orderAmounts.Add(dataPoint.TotalAmount);
                            orderCounts.Add(dataPoint.Count);

                        }
                        else
                        {
                            orderAmounts.Add(0);
                            orderCounts.Add(0);

                        }
                    }
                }
                else
                {
                    // 周/月视图：按天映射数据
                    var startDateForGrouping = startDate.Date;
                    for (int i = 0; i < timeLabels.Count; i++)
                    {
                        var currentDate = startDateForGrouping.AddDays(i);
                        // 使用精确的日期比较
                        var dataPoint = chartDataPoints.FirstOrDefault(x => 
                            x.Date.HasValue && 
                            Math.Abs((x.Date.Value.Date - currentDate).TotalDays) < 0.1);
                        
                        if (dataPoint != null)
                        {
                            orderAmounts.Add(dataPoint.TotalAmount);
                            orderCounts.Add(dataPoint.Count);

                        }
                        else
                        {
                            orderAmounts.Add(0);
                            orderCounts.Add(0);

                        }
                    }
                }
                
                // 6. 设置图表数据
                chartData.OrderAmounts = orderAmounts;
                chartData.OrderCounts = orderCounts;



                return new ApiResult<ChartDataDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = chartData };
            }
            catch (Exception ex)
            {
                return new ApiResult<ChartDataDto> { Code = ApiEnum.Error, Msg = $"获取销售图表数据失败: {ex.Message}" };
            }
        }

        /// <summary>
        /// 获取采购统计图表数据 - 重新设计，确保数据真实一致
        /// </summary>
        public async Task<ApiResult<ChartDataDto>> GetPurchaseChartDataAsync(string timeRange)
        {
            try
            {

                
                var chartData = new ChartDataDto
                {
                    TimeRange = timeRange,
                    Type = "purchase"
                };

                // 1. 根据时间范围计算开始和结束日期
                var (startDate, endDate) = GetDateRange(timeRange);
                var timeLabels = GetTimeLabels(timeRange);



                // 2. 查询图表数据
                var chartDataPoints = await _queryOptimizationService.GetChartDataOptimizedAsync<PurchaseOrderModel>(
                    startDate, endDate, timeRange);



                // 3. 设置时间标签
                chartData.TimeLabels = timeLabels;
                
                // 4. 确保数据点数量与时间标签数量匹配
                var orderAmounts = new List<decimal>();
                var orderCounts = new List<int>();
                
                // 5. 根据时间范围选择不同的数据映射策略
                if (timeRange == "year")
                {
                    // 年度视图：按月映射数据
                    var startDateForGrouping = startDate.Date;
                    for (int i = 0; i < timeLabels.Count; i++)
                    {
                        var currentMonth = startDateForGrouping.AddMonths(i);
                        var dataPoint = chartDataPoints.FirstOrDefault(x => 
                            x.Date.HasValue && 
                            x.Date.Value.Year == currentMonth.Year && 
                            x.Date.Value.Month == currentMonth.Month);
                        
                        if (dataPoint != null)
                        {
                            orderAmounts.Add(dataPoint.TotalAmount);
                            orderCounts.Add(dataPoint.Count);

                        }
                        else
                        {
                            orderAmounts.Add(0);
                            orderCounts.Add(0);

                        }
                    }
                }
                else
                {
                    // 周/月视图：按天映射数据
                    var startDateForGrouping = startDate.Date;
                    for (int i = 0; i < timeLabels.Count; i++)
                    {
                        var currentDate = startDateForGrouping.AddDays(i);
                        // 使用精确的日期比较
                        var dataPoint = chartDataPoints.FirstOrDefault(x => 
                            x.Date.HasValue && 
                            Math.Abs((x.Date.Value.Date - currentDate).TotalDays) < 0.1);
                        
                        if (dataPoint != null)
                        {
                            orderAmounts.Add(dataPoint.TotalAmount);
                            orderCounts.Add(dataPoint.Count);

                        }
                        else
                        {
                            orderAmounts.Add(0);
                            orderCounts.Add(0);

                        }
                    }
                }
                
                // 6. 设置图表数据
                chartData.OrderAmounts = orderAmounts;
                chartData.OrderCounts = orderCounts;



                return new ApiResult<ChartDataDto> { Code = ApiEnum.Success, Msg = "获取成功", Data = chartData };
            }
            catch (Exception ex)
            {
                return new ApiResult<ChartDataDto> { Code = ApiEnum.Error, Msg = $"获取采购图表数据失败: {ex.Message}" };
            }
        }

        /// <summary>
        /// 获取时间范围
        /// </summary>
        private (DateTime startDate, DateTime endDate) GetDateRange(string timeRange)
        {
            var now = DateTime.Now;
            var endDate = now.Date.AddDays(1).AddSeconds(-1); // 今天的最后一秒

            var startDate = timeRange switch
            {
                "week" => now.Date.AddDays(-6), // 最近7天（包含今天，从7天前开始）
                "month" => now.Date.AddDays(-30), // 最近31天
                "year" => now.Date.AddMonths(-11), // 最近12个月
                _ => now.Date.AddDays(-6) // 默认最近7天
            };

            // 对于月视图和年视图，不强制限制最早数据日期，让数据自然显示
            // 这样可以确保时间标签和数据范围完全匹配
            if (timeRange == "week")
            {
                // 周视图：确保开始日期不早于数据库中最老的数据
                var earliestDataDate = new DateTime(2025, 8, 1); // 根据您的数据调整
                if (startDate < earliestDataDate)
                {
                    startDate = earliestDataDate;
                }
            }



            return (startDate, endDate);
        }

        /// <summary>
        /// 获取时间标签
        /// </summary>
        private List<string> GetTimeLabels(string timeRange)
        {
            var now = DateTime.Now;
            var labels = new List<string>();

            switch (timeRange)
            {
                case "week":
                    // 往前推6天，加上今天，总共7天，格式为 "月/日"
                    for (int i = 6; i >= 0; i--)
                    {
                        var date = now.Date.AddDays(-i);
                        labels.Add($"{date.Month}/{date.Day}");
                    }
                    break;
                case "month":
                    // 往前推30天，加上今天，总共31天，格式为 "月/日"
                    for (int i = 30; i >= 0; i--)
                    {
                        var date = now.Date.AddDays(-i);
                        labels.Add($"{date.Month}/{date.Day}");
                    }
                    break;
                case "year":
                    // 往前推11个月，加上当前月，总共12个月，格式为 "月"
                    for (int i = 11; i >= 0; i--)
                    {
                        var date = now.Date.AddMonths(-i);
                        labels.Add($"{date.Month}月");
                    }
                    break;
                default:
                    // 默认最近1周
                    for (int i = 6; i >= 0; i--)
                    {
                        var date = now.Date.AddDays(-i);
                        labels.Add($"{date.Month}/{date.Day}");
                    }
                    break;
            }



            return labels;
        }

        /// <summary>
        /// 按时间分组统计数据
        /// </summary>
        private List<ChartDataPoint> GroupDataByTime<T>(List<T> orders, string timeRange, DateTime startDate, DateTime endDate) where T : class
        {
            var result = new List<ChartDataPoint>();

            if (timeRange == "week" || timeRange == "month")
            {
                // 按天分组
                for (int i = 0; i < (timeRange == "week" ? 7 : 31); i++)
                {
                    var date = startDate.AddDays(i);
                    var dayOrders = orders.Where(x => GetOrderDate(x) >= date.Date && GetOrderDate(x) < date.Date.AddDays(1)).ToList();
                    
                    result.Add(new ChartDataPoint
                    {
                        TotalAmount = dayOrders.Sum(x => GetOrderAmount(x)),
                        Count = dayOrders.Count
                    });
                }
            }
            else if (timeRange == "year")
            {
                // 按月分组
                for (int i = 0; i < 12; i++)
                {
                    var monthStart = startDate.AddMonths(i);
                    var monthEnd = monthStart.AddMonths(1);
                    var monthOrders = orders.Where(x => GetOrderDate(x) >= monthStart && GetOrderDate(x) < monthEnd).ToList();
                    
                    result.Add(new ChartDataPoint
                    {
                        TotalAmount = monthOrders.Sum(x => GetOrderAmount(x)),
                        Count = monthOrders.Count
                    });
                }
            }

            return result;
        }

        /// <summary>
        /// 获取订单日期
        /// </summary>
        private DateTime GetOrderDate(object order)
        {
            return order switch
            {
                ProductionSalesOrderModel salesOrder => salesOrder.CreateTime,
                PurchaseOrderModel purchaseOrder => purchaseOrder.CreateTime,
                _ => DateTime.Now
            };
        }

        /// <summary>
        /// 获取订单金额
        /// </summary>
        private decimal GetOrderAmount(object order)
        {
            return order switch
            {
                ProductionSalesOrderModel salesOrder => salesOrder.TotalAmount,
                PurchaseOrderModel purchaseOrder => purchaseOrder.TotalAmount,
                _ => 0
            };
        }

        /// <summary>
        /// 图表数据点
        /// </summary>
        private class ChartDataPoint
        {
            public decimal TotalAmount { get; set; }
            public int Count { get; set; }
        }

        #endregion


    }
} 